const db = require('../db/db-connectivity')
var jwt = require('jsonwebtoken')
const { secret } = require('../utils/config')
const crypto = require('crypto')
module.exports = {
  // 1.登录业务
  login: async (req, res, next) => {
    const data = req.body
    const sqlStr = 'select * from shop_users where username=? '
    // console.log(data);
    const [finalRes] = await db.query(sqlStr, data.username)
    // console.log(finalRes);
    //判断是否拥有该账户
    if (finalRes.length > 0) {
      //1.1存在账号,与传过来的密码加密后和数据库对比
      //
      const hash = crypto
        .createHmac('sha256', secret)
        .update(data.username + data.password + '另一个私钥')
        .digest('hex')
      if (finalRes[0].password === hash) {
        //密码符合，发送token 写入cookie
        const tokenStr = jwt.sign({ username: data.username }, secret, {
          expiresIn: '1h',
        })
        res.cookie('token', 'Bearer ' + tokenStr, {
          maxAge: 3600000,
          httpOnly: true,
        })
        return res.send({
          status: 200,
          message: '登录成功',
          token: 'Bearer ' + tokenStr,
        })
      } //1.2 存在账号密码不符合
      return res.send({
        status: 401,
        message: '密码错误',
      })
    } else {
      res.send({
        status: 401,
        message: '用户不存在',
      })
    }
  },
  //页面渲染业务
  renderhtml: (req, res, next) => {
    //1判断是否有token，无则渲染登录页面

    //2有token 重定向到index页面
    res.type('html')
    res.render('login.html')
  },
}
